package com.liang.paul.officelite.utils;

import android.os.AsyncTask;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by paulliang on 16/4/29.
 */
public class FileDownloadTask extends AsyncTask<String, Integer, Boolean> {

    Callback callback;
    String path;

    public FileDownloadTask(String path, Callback callback){
        this.callback = callback;
        this.path = path;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        try {
            int size = -1;
            int downloadedSize = 0;
            URL url = new URL(params[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setRequestProperty("User-Agent",
                    " Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)");
            if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
                size = connection.getContentLength();
                InputStream inputStream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                FileOutputStream fileOutputStream = new FileOutputStream(path);
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1){
                    fileOutputStream.write(buffer, 0, len);
                    downloadedSize += len;
                    publishProgress((downloadedSize / size) * 100);
                    return true;
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        callback.onProgress(values[0]);
    }

    @Override
    protected void onPostExecute(Boolean flag) {
        super.onPostExecute(flag);

        if(flag) {
            File file = new File(path);
            callback.onRespond(file);
        }else {
            callback.onFailed("下载失败");
        }
    }

    public interface Callback{
        public void onProgress(int progress);
        public void onRespond(Object object);
        public void onFailed(String err);
    }

}
